package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysOssPartDetail;
import com.ruoyi.system.service.ISysOssPartDetailService;
import lombok.SneakyThrows;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用来将文件分片上传记录保存到数据库
 * 目前仅手动分片分片上传时使用
 *
 * @author fengcheng
 */
@Service
public class FilePartDetailServiceImpl {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ISysOssPartDetailService sysOssPartDetailService;

    /**
     * 保存文件分片信息
     *
     * @param info 文件分片信息
     */
    @SneakyThrows
    public void saveFilePart(FilePartInfo info) {
        SysOssPartDetail detail = toFilePartDetail(info);
        detail.setCreateTime(DateUtils.getNowDate());
        detail.setCreator(SecurityUtils.getUserId());
        if (sysOssPartDetailService.insertSysOssPartDetail(detail) > 0) {
            info.setId(detail.getOssPartDetailId());
        }
    }

    /**
     * 删除文件分片信息
     */
    public void deleteFilePartByUploadId(String uploadId) {
        sysOssPartDetailService.removeByUploadId(uploadId);
    }

    /**
     * 将 FilePartInfo 转成 FilePartDetail
     *
     * @param info 文件分片信息
     */
    public SysOssPartDetail toFilePartDetail(FilePartInfo info) throws JsonProcessingException {
        SysOssPartDetail detail = new SysOssPartDetail();
        detail.setPlatform(info.getPlatform());
        detail.setUploadId(info.getUploadId());
        detail.setETag(info.getETag());
        detail.setPartNumber(info.getPartNumber());
        detail.setPartSize(info.getPartSize());
        detail.setHashInfo(valueToJson(info.getHashInfo()));
        detail.setCreateTime(info.getCreateTime());
        return detail;
    }

    /**
     * 将指定值转换成 json 字符串
     */
    public String valueToJson(Object value) throws JsonProcessingException {
        if (value == null) return null;
        return objectMapper.writeValueAsString(value);
    }
}
